package com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.repository.HddcStrongseismiccatalogNativeRepository;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.repository.HddcStrongseismiccatalogRepository;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.repository.entity.HddcStrongseismiccatalogEntity;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.service.HddcStrongseismiccatalogService;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.viewobjects.HddcStrongseismiccatalogPageVO;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.viewobjects.HddcStrongseismiccatalogQueryParams;
import com.css.zfzx.sjcj.modules.hddcStrongSeismicCatalog.viewobjects.HddcStrongseismiccatalogVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-28
 */
@Service
public class HddcStrongseismiccatalogServiceImpl implements HddcStrongseismiccatalogService {

    private final HddcStrongseismiccatalogRepository hddcStrongseismiccatalogRepository;
    private final HddcStrongseismiccatalogNativeRepository hddcStrongseismiccatalogNativeRepository;
    private final StrongseismicCatelogsBefor1970_4_3_4ExcelVerifyHandler strongseismiccatelogExcelVerifyHandler;

    @Autowired
    public HddcStrongseismiccatalogServiceImpl(HddcStrongseismiccatalogRepository hddcStrongseismiccatalogRepository,
                                               HddcStrongseismiccatalogNativeRepository hddcStrongseismiccatalogNativeRepository,
                                               StrongseismicCatelogsBefor1970_4_3_4ExcelVerifyHandler strongseismiccatelogExcelVerifyHandler) {
        this.hddcStrongseismiccatalogRepository = hddcStrongseismiccatalogRepository;
        this.hddcStrongseismiccatalogNativeRepository = hddcStrongseismiccatalogNativeRepository;
        this.strongseismiccatelogExcelVerifyHandler = strongseismiccatelogExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcStrongseismiccatalogs(HddcStrongseismiccatalogQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcStrongseismiccatalogPageVO> hddcStrongseismiccatalogPage = this.hddcStrongseismiccatalogNativeRepository.queryHddcStrongseismiccatalogs(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcStrongseismiccatalogPage);
    }


    @Override
    public HddcStrongseismiccatalogEntity getHddcStrongseismiccatalog(String id) {
        return this.hddcStrongseismiccatalogRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStrongseismiccatalogEntity saveHddcStrongseismiccatalog(HddcStrongseismiccatalogEntity hddcStrongseismiccatalog) {
        String uuid = UUIDGenerator.getUUID();
        hddcStrongseismiccatalog.setUuid(uuid);
        hddcStrongseismiccatalog.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcStrongseismiccatalog.setCreateTime(now);
        hddcStrongseismiccatalog.setUpdateTime(now);
        hddcStrongseismiccatalog.setIsValid(PlatformConstants.Y);
        hddcStrongseismiccatalog.setQualityinspectionStatus(PlatformConstants.N);
        hddcStrongseismiccatalog.setExtends10(PlatformConstants.Y);
        this.hddcStrongseismiccatalogRepository.save(hddcStrongseismiccatalog);
        return hddcStrongseismiccatalog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStrongseismiccatalogEntity updateHddcStrongseismiccatalog(HddcStrongseismiccatalogEntity hddcStrongseismiccatalog) {
        HddcStrongseismiccatalogEntity entity = hddcStrongseismiccatalogRepository.findById(hddcStrongseismiccatalog.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcStrongseismiccatalog);
        hddcStrongseismiccatalog.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcStrongseismiccatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcStrongseismiccatalogRepository.save(hddcStrongseismiccatalog);
        return hddcStrongseismiccatalog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcStrongseismiccatalogs(List<String> ids) {
        List<HddcStrongseismiccatalogEntity> hddcStrongseismiccatalogList = this.hddcStrongseismiccatalogRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcStrongseismiccatalogList) && hddcStrongseismiccatalogList.size() > 0) {
            for(HddcStrongseismiccatalogEntity hddcStrongseismiccatalog : hddcStrongseismiccatalogList) {
                hddcStrongseismiccatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStrongseismiccatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStrongseismiccatalog.setIsValid("0");
                this.hddcStrongseismiccatalogRepository.save(hddcStrongseismiccatalog);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcStrongseismiccatalogEntity> hddcStrongseismiccatalogList = this.hddcStrongseismiccatalogRepository.queryHddcStrongseismiccatalogsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcStrongseismiccatalogList) && hddcStrongseismiccatalogList.size() > 0) {
            for(HddcStrongseismiccatalogEntity hddcStrongseismiccatalog : hddcStrongseismiccatalogList) {
                hddcStrongseismiccatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStrongseismiccatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStrongseismiccatalog.setIsValid("0");
                this.hddcStrongseismiccatalogRepository.save(hddcStrongseismiccatalog);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcStrongseismiccatalogEntity> hddcStrongseismiccatalogList = this.hddcStrongseismiccatalogRepository.queryHddcStrongseismiccatalogsByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcStrongseismiccatalogList) && hddcStrongseismiccatalogList.size() > 0) {
            for(HddcStrongseismiccatalogEntity hddcStrongseismiccatalog : hddcStrongseismiccatalogList) {
                hddcStrongseismiccatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStrongseismiccatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStrongseismiccatalog.setIsValid("0");
                this.hddcStrongseismiccatalogRepository.save(hddcStrongseismiccatalog);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcStrongseismiccatalogQueryParams queryParams, HttpServletResponse response) {
        List<HddcStrongseismiccatalogEntity> yhDisasterEntities = hddcStrongseismiccatalogNativeRepository.exportYhDisasters(queryParams);
        List<HddcStrongseismiccatalogVO> list=new ArrayList<>();
        for (HddcStrongseismiccatalogEntity entity:yhDisasterEntities) {
            HddcStrongseismiccatalogVO yhDisasterVO=new HddcStrongseismiccatalogVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"1970年前4 3_4以上强震目录-点","1970年前4 3_4以上强震目录-点",HddcStrongseismiccatalogVO.class,"1970年前4 3_4以上强震目录-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(strongseismiccatelogExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcStrongseismiccatalogVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcStrongseismiccatalogVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcStrongseismiccatalogVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcStrongseismiccatalogVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     */
    public void saveDisasterList(List<HddcStrongseismiccatalogVO> list) {
        for (HddcStrongseismiccatalogVO hddcStrongseismiccatalogVO : list) {
            HddcStrongseismiccatalogEntity yhDisasterEntity = new HddcStrongseismiccatalogEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcStrongseismiccatalogVO, yhDisasterEntity);
            saveHddcStrongseismiccatalog(yhDisasterEntity);
        }
    }

}
